/* eslint-disable prettier/prettier */
<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="showMap ? 6 : 24">
        <el-card class="marker-list" body-style="padding: 0 10px" style="height: 100%">
          <template #header>
            <span>点位列表</span>
            <el-button type="primary" size="small" style="float: right" @click="OpenAddMarkerDialog">添加点位</el-button>
            <el-button size="small" style="float: right; margin-right: 10px" @click="showMapOrNot">{{
              showMap ? "收起地图" : "展开地图"
            }}</el-button>
            <el-button size="small" style="float: right" @click="clearFilter">重置列表</el-button>
          </template>
          <!--tag 筛选点位-->
          <el-card>
            <div class="flex gap-2 mt-4">
              <span>机组</span>
              <el-tag
                v-for="item in units_tag"
                :key="item.value"
                :checked="item.checked"
                @click="TagChange(item)"
                :type="item.checked ? 'primary' : 'info'"
                effect="light"
                round
                style="margin-left: 10px"
              >
                {{ item.value }}
              </el-tag>
            </div>
            <!--可扩展更多可用来筛选的tag-->
          </el-card>
          <el-table ref="tableRef" :data="tableData" height="100%" border class="custom-table">
            <el-table-column type="selection" :selectable="selected" width="55" />
            <el-table-column prop="mapDetailDesc" label="点位名称"></el-table-column>
            <el-table-column
              prop="unitName"
              label="机组"
              :filters="units"
              :filter-method="filterUnit"
              filter-placement="bottom-end"
            >
            </el-table-column>
            <el-table-column prop="nfcName" label="点位编码"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="warning" size="small" @click="OpenEditMarkerDialog(scope.row)" text style="padding: 0 0">
                  修改
                </el-button>
                <el-button type="danger" @click="deleteMarker(scope.row)" size="small" text style="padding: 0 0">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card id="map-container" v-show="showMap"> </el-card>
        <div id="panel" v-show="showMap"></div>
      </el-col>
    </el-row>
    <el-dialog title="添加点位" v-model="showAddMarkerDialog" width="500px">
      <!-- 表单 -->
      <el-form :model="addForm" ref="addFormRef" label-width="120px" :rules="addRules">
        <el-form-item label="点位名称" prop="mapDetailDesc">
          <el-input v-model="addForm.mapDetailDesc"></el-input>
        </el-form-item>
        <el-form-item label="地图ID" prop="mapId">
          <el-input v-model.number="addForm.mapId" type="number" disabled></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="mapLatitude">
          <el-input v-model="addForm.mapLatitude"></el-input>
        </el-form-item>
        <el-form-item label="经度" prop="mapLongitude">
          <el-input v-model="addForm.mapLongitude"></el-input>
        </el-form-item>
        <el-form-item label="机组" prop="unitId">
          <el-select v-model="addForm.unitId" placeholder="选择机组" clearable>
            <el-option v-for="unit in unitArray" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位编码" prop="mapNfcMsg">
          <el-select v-model="addForm.mapNfcMsg" placeholder="选择编码" clearable>
            <el-option v-for="nfc in NfcArray" :key="nfc.nfcName" :label="nfc.nfcName" :value="nfc.nfcMsg"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showAddMarkerDialog = false">取消</el-button>
        <el-button type="primary" @click="ConfirmAddMarker">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改点位信息" v-model="showEditMarkerDialog" width="500px" style="border-radius: 8px">
      <!-- 表单 -->
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="addRules">
        <el-form-item label="点位名称" prop="mapDetailDesc">
          <el-input v-model="editForm.mapDetailDesc"></el-input>
        </el-form-item>
        <el-form-item label="机组" prop="unitId">
          <el-select v-model="editForm.unitId" placeholder="选择机组" clearable>
            <el-option v-for="unit in unitArray" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="编码信息" prop="mapNfcMsg">
          <el-select v-model="editForm.mapNfcMsg" placeholder="选择编码" clearable>
            <el-option v-for="nfc in NfcArray" :key="nfc.nfcName" :label="nfc.nfcName" :value="nfc.nfcMsg"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showEditMarkerDialog = false">取消</el-button>
        <el-button type="primary" @click="ConfirmEditMarker">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="js">
import { onMounted, onUnmounted, reactive, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import request from "@/api/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import iconImage1 from "@/assets/icons/locationpng.png";

const mapId = 1;
let map = null;
let icon = null;
const showAddMarkerDialog = ref(false);
const showEditMarkerDialog = ref(false);
const showMap = ref(false);
const addForm = reactive({
  mapDetailDesc: "",
  mapId: 0,
  mapLatitude: "",
  mapLongitude: "",
  unitId: null,
  mapNfcMsg: ""
});
const addFormRef = ref(null);
const editForm = reactive({});
const editFormRef = ref(null);
const addRules = {
  mapDetailDesc: [{ required: true, message: "请输入点位名称", trigger: "blur" }],
  mapLongitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
  mapLatitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
  unitId: [{ required: true, message: "请选择机组", trigger: "blur" }],
  mapNfcMsg: [{ required: true, message: "请选择编码信息", trigger: "blur" }]
};

// let yourPosition;
// let city;
let clickPoint = [];

const detailData = ref([]);
let markers = [];

const pointData = ref([]);
const unitArray = ref([]);
const NfcArray = ref([]);
const units = ref([]);
const units_tag = ref([]);

const make_unit_filter = () => {
  unitArray.value.forEach(item => {
    units.value.push({
      text: item.unitName,
      value: item.unitName
    });
    units_tag.value.push({
      value: item.unitName,
      checked: false
    });
    console.log(units_tag.value);
  });
};

onMounted(async () => {
  await getAllPoints();
  tableData.value = pointData.value;
  getAllNFCs();
  getAllUnits();
  window._AMapSecurityConfig = {
    securityJsCode: "701b2c8adf1951bafc116e4a916cf996"
  };
  AMapLoader.load({
    key: "dd93fce2d1e6b0eb1d3e438c7a2581c0", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.Scale",
      "AMap.ControlBar",
      "AMap.MapType",
      "AMap.ToolBar",
      "AMap.Marker",
      "AMap.PlaceSearch",
      "AMap.Geolocation"
    ] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then(AMap => {
      map = new AMap.Map("map-container", {
        // 设置地图容器id
        viewMode: "2D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        resizeEnable: true
      });

      const placeSearch = new AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        map: map, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      });

      icon = new AMap.Icon({
        size: new AMap.Size(30, 40), //图标尺寸
        image: iconImage1, //Icon 的图像
        imageOffset: new AMap.Pixel(-2, 0), //图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 40) //根据所设置的大小拉伸或压缩图片
      });

      const marker = new AMap.Marker({
        offset: [0, 6],
        zIndex: 99
      });
      map.add(marker);

      map.on("click", function (e) {
        clickPoint = [e.lnglat.getLng(), e.lnglat.getLat()];
        // const distance = AMap.GeometryUtil.distance(yourPosition, clickPoint);

        // 自定义点标记内容
        const markerContent = document.createElement("div");
        // 点标记中的图标
        const markerImg = document.createElement("img");
        markerImg.className = "markerlnglat";
        markerImg.src = "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png";
        markerImg.setAttribute("width", "25px");
        markerImg.setAttribute("height", "34px");
        markerContent.appendChild(markerImg);

        // const markerSpan = document.createElement("div");
        // markerSpan.className = "marker";
        // markerSpan.style =
        //   "position: absolute;\n" +
        //   "  top: -32px;\n" +
        //   "  left: 20px;\n" +
        //   "  padding: 4px 10px;\n" +
        //   "  font-size: 12px;\n" +
        //   "  color: #ffffff;\n" +
        //   "  white-space: nowrap;\n" +
        //   "  background-color: #25a5f7;\n" +
        //   "  border-radius: 3px;\n" +
        //   "  box-shadow: 1px 1px 1px rgb(10 10 10 / 20%);";
        // markerSpan.innerHTML = "距离您" + Math.round(distance) + "米";
        // markerContent.appendChild(markerSpan);

        marker.setContent(markerContent);
        marker.setPosition(clickPoint);
      });

      const controlBar = new AMap.ControlBar();
      map.addControl(controlBar);

      const scale = new AMap.Scale();
      map.addControl(scale);

      const toolBar = new AMap.ToolBar();
      map.addControl(toolBar);

      // 在地图时启用定位
      // 初始化 Geolocation 插件
      // const geolocation = new AMap.Geolocation({
      //   enableHighAccuracy: true, // 是否使用高精度定位，默认：true
      //   timeout: 10000, // 设置定位超时时间，默认：无穷大
      //   offset: [20, 90], // 定位按钮的停靠位置的偏移量
      //   zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      //   position: "RB" // 定位按钮的排放位置,  RB表示右下
      // });

      // map.addControl(geolocation);
      //
      // geolocation.getCurrentPosition((status, result) => {
      //   if (status === "complete") {
      //     onComplete(result);
      //   } else {
      //     onError(result);
      //   }
      // });
      onComplete();
      // 调整地图视野以包含所有标记
      map.setFitView(markers);

      function onComplete() {
        // data是具体的定位信息
        // const position = data.position;
        // map.setCenter(position); // 将地图中心点设置为定位
        // longitude.value = position.lng;
        // latitude.value = position.lat;
        // yourPosition = [position.lng, position.lat];
        // console.log("定位成功", yourPosition);
        pointData.value.forEach(detail => {
          const point = [detail.mapLongitude, detail.mapLatitude];
          const label = { content: detail.mapDetailDesc, offset: [10, -10] };
          // const distance = AMap.GeometryUtil.distance(yourPosition, point);
          // const content = "距离您" + Math.round(distance) + "米";
          const detailMarker = new AMap.Marker({
            icon: icon,
            clickable: false,
            label: label,
            // title: content,
            position: point,
            extData: detail,
            offset: [-18, -40],
            map: map
          });
          markers.push(detailMarker);
        });
      }

      // function onError(data) {
      //   // 定位出错
      //   console.error("定位失败", data);
      // }

      // geolocation.getCityInfo((status, result) => {
      //   if (status === "complete") {
      //     city = result.city;
      //     placeSearch = new AMap.PlaceSearch({
      //       city: city,
      //       pageSize: 5, // 单页显示结果条数
      //       pageIndex: 1, // 页码
      //       map: map, // 展现结果的地图实例
      //       panel: "panel", // 结果列表将在此容器中进行展示。
      //       autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      //     });
      //   } else {
      //     onError(result);
      //   }
      // });

      // 其他插件初始化和地图相关的代码
      map.plugin(["AMap.AutoComplete"], function () {
        const autoOptions = {
          //使用联想输入的 input 的 id
          input: "searchInput"
        };
        const autocomplete = new AMap.AutoComplete(autoOptions);
        autocomplete.on("select", function (e) {
          //针对选中的poi实现自己的功能
          placeSearch.search(e.poi.name);
        });
      });
    })
    .catch(e => {
      console.log(e);
    });
});
const getAllNFCs = () => {
  request.get("/api-self/NFC").then(res => {
    const data = res.data;
    if (data.code === 0) {
      NfcArray.value = data.data;
    } else {
      ElMessage.error("获取编码信息失败：" + data.message);
    }
  });
};
const getAllUnits = () => {
  request.get("/api-self/users/unit/getUnits").then(res => {
    const data = res.data;
    if (data.code === 0) {
      unitArray.value = data.data;
      make_unit_filter();
    } else {
      ElMessage.error("获取机组数据失败：" + data.message);
    }
  });
};
const tableRef = ref();
//过滤器
const filterUnit = (value, row) => {
  return row.unitName === value;
};
const clearFilter = () => {
  if (tableRef.value) {
    tableRef.value.clearFilter();
  }
};

const deleteMarker = row => {
  console.log("delete:" + row.mapDetailId);
  ElMessageBox.confirm("将会删除这个点位，确定吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    request.delete("/api-self/inspection/map/detail/" + row.mapDetailId).then(res => {
      const data = res.data;
      if (data.code === 0) {
        removeDetailById(row.mapDetailId);
        ElMessage.success("删除成功");
        getAllPoints();
      } else {
        ElMessage.error("删除失败：" + data.message);
      }
    });
  });
};
const removeDetailById = id => {
  let index = detailData.value.findIndex(detail => detail.mapDetailId === id);
  if (index !== -1) {
    detailData.value.splice(index, 1);
  }
  index = markers.findIndex(marker => marker.getExtData().mapDetailId === id);
  if (index !== -1) {
    markers[index].setMap(null);
    markers.splice(index, 1);
  }
};
const OpenAddMarkerDialog = () => {
  showAddMarkerDialog.value = true;
  addForm.mapId = mapId;
  if (clickPoint.length > 1) {
    addForm.mapLongitude = clickPoint[0].toString();
    addForm.mapLatitude = clickPoint[1].toString();
  }
};
const ConfirmAddMarker = () => {
  console.log(editForm);
  addFormRef.value.validate(valid => {
    if (valid) {
      request.post("/api-self/inspection/map/mapDetail", addForm).then(res => {
        const data = res.data;
        if (data.code === 0) {
          getAllPoints();
          addNewMarkerToMap();
          ElMessage.success("添加成功");
          showAddMarkerDialog.value = false;
        } else {
          ElMessage.error("添加失败：" + data.message);
        }
      });
    }
  });
};
const OpenEditMarkerDialog = row => {
  showEditMarkerDialog.value = true;
  editForm.mapDetailDesc = row.mapDetailDesc;
  editForm.mapDetailId = row.mapDetailId;
  editForm.mapId = 1;
  editForm.mapNfcMsg = row.mapNfcMsg;
  editForm.unitId = row.unitId;
};
const ConfirmEditMarker = () => {
  editFormRef.value.validate(valid => {
    if (valid) {
      console.log("Edit", editForm);
      request.put("/api-self/inspection/map/detail", editForm).then(res => {
        const data = res.data;
        if (data.code === 0) {
          ElMessage.success("修改成功");
          getAllPoints();
          markers
            .find(marker => marker.getExtData().mapDetailId === editForm.mapDetailId)
            .setLabel({ content: editForm.mapDetailDesc, offset: [10, -10] });
          showEditMarkerDialog.value = false;
        } else {
          ElMessage.error("修改失败：" + data.message);
        }
      });
    }
  });
};
const addNewMarkerToMap = () => {
  detailData.value.push(addForm);
  const point = [addForm.mapLongitude, addForm.mapLatitude];
  const label = { content: addForm.mapDetailDesc, offset: [10, -10] };
  // const distance = AMap.GeometryUtil.distance(yourPosition, point);
  // const content = "距离您" + Math.round(distance) + "米";
  const newMarker = new AMap.Marker({
    icon: icon,
    clickable: false,
    label: label,
    // title: content,
    position: point,
    extData: addForm,
    offset: [-18, -40]
  });
  map.add(newMarker);
  markers.push(newMarker);
};
const getAllPoints = async () => {
  await request.get("/api-self/inspection/map/1").then(res => {
    const data = res.data;
    if (data.code === 0) {
      pointData.value = data.data;
    } else {
      ElMessage.error("获取可选点位信息失败：" + data.message);
    }
  });
};
onUnmounted(() => {
  map?.destroy();
});

const selected = () => {
  return true;
};

const showMapOrNot = () => {
  showMap.value = !showMap.value;
};

//tags 相关
// 定义一个方法来处理标签选中状态的变化

const tags = ref([]);
const TagChange = item => {
  item.checked = !item.checked;
  if (item.checked) {
    if (!tags.value.includes(item.value)) {
      tags.value.push(item.value);
    }
  } else {
    const index = tags.value.indexOf(item.value);
    if (index !== -1) {
      tags.value.splice(index, 1);
    }
  }
  filteredPointData();
  console.log("tags", tags.value);
};

const tableData = ref([]);

const filteredPointData = () => {
  if (tags.value.length) {
    tableData.value = pointData.value.filter(point => {
      return !tags.value.length || tags.value.includes(point.unitName);
    });
  } else {
    tableData.value = pointData.value;
  }
};
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 85vh;
}
.marker-list {
  width: 100%;
  height: 74vh;
}
#panel {
  position: fixed;
  top: 200px;
  right: 20px;
  width: 300px;
  max-height: 90%;
  overflow-y: auto;
  background-color: white;
  border-bottom: solid 0 silver;
}
.custom-table :deep(.el-table__header-wrapper thead tr th) {
  color: #000000;
  text-align: center;
  background-color: #fafafa;
}
.custom-table :deep(.el-table__body-wrapper tbody tr td) {
  text-align: center; /* 单元格内容居中 */
}
</style>
